package com.zhp;

import com.zhp.common.R;
import com.zhp.ex.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.zhp.common.R.*;
/**
 * @author zhanghp
 * @since 2024/5/16 17:33
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {


    /**
     * 自定义全局异常处理调用方法
     *
     * @param ex 异常信息
     * @return R
     */
    public  R<?> allExceptionHandler(Throwable ex){
        // 自定义异常
        if (ex instanceof CustomException) {
            return customExceptionHandler((CustomException) ex);
        }
        return exceptionHandler(ex);
    }

    @ExceptionHandler(Exception.class)
    public R<?> exceptionHandler(Throwable ex){
        log.warn("[exception]");
        return fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
    }

    @ExceptionHandler(value = CustomException.class)
    public R<?> customExceptionHandler(CustomException e) {
        log.warn("[CustomException]");
        return fail(e.getCode(), e.getMsg());
    }
}
